package com.strive.exception;

import com.alibaba.fastjson.JSON;
import com.strive.common.model.base.RequestModel;
import com.strive.common.model.base.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/3/2 14:18
 * @Version 1.0
 */
@Component
public class CustomException extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        try {
            if(authException instanceof BadCredentialsException){

                response.setStatus(7777);
                response.setHeader("Content-Type","application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(Result.succeed(authException.getMessage())));
            }else if(authException instanceof InsufficientAuthenticationException){
                response.setStatus(6666);
                response.setHeader("Content-Type","application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(Result.succeed(authException.getMessage())));
            }else{
                super.commence(request,response,authException);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            RequestModel.removeRequestModel();
        }
    }
}
